import sys
import tornado.web
import tornado.ioloop
from os.path import abspath, join, dirname


def run_server():
    """
    启动服务器
    :return:
    """
    from server.MainHandler import MainHandler
    from server.config import server_port

    application = tornado.web.Application([
        (r'/', MainHandler),
    ])

    application.listen(server_port)
    print('server ready')
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    # 模块路径引用
    sys.path.append(abspath(join(dirname(__file__), '..')))
    from server.check_resource import check_resource
    # 先检查资源是否完整
    check_resource()
    
    if len(sys.argv) == 1:
        # 默认启动服务器
        run_server()
    elif len(sys.argv) == 2:
        arg = sys.argv[1]
        if arg == 'server':
            # 启动服务器
            run_server()
        elif arg == 'init_db':
            # 数据库初始化
            from neo4j.data_operation import init_db

            init_db()
        elif arg == 'clear_db':
            # 清除数据库数据
            from neo4j.data_operation import clear_db

            clear_db()
        else:
            sys.stderr.write('error: unknown argument:', arg)
    else:
        sys.stderr.write('error: too many arguments')
